<template>
  <el-form ref="formRef" :model="model" :rules="rules" label-width="100px">
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
      <!-- 左侧：可编辑信息 -->
      <el-card shadow="never" class="form-card">
        <template #header>
          <h3 class="text-lg font-semibold">基本信息</h3>
        </template>

        <div class="space-y-4">
          <el-form-item label="名称" prop="name">
            <el-input v-model="model.name" placeholder="请输入名称" />
          </el-form-item>
          <el-form-item label="URL" prop="url">
            <el-input v-model="model.url" placeholder="请输入 RSS 地址" />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="model.status">
              <el-radio :label="1">启用</el-radio>
              <el-radio :label="0">禁用</el-radio>
            </el-radio-group>
          </el-form-item>

          <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
            <el-form-item label="抓取时间" prop="fetchTime">
              <el-time-picker v-model="time" placeholder="选择时间" format="HH:mm:ss" value-format="HH:mm:ss" class="w-full" />
            </el-form-item>
            <el-form-item label="RSS 版本" prop="rssVersion">
              <el-select v-model="model.rssVersion" class="w-full">
                <el-option value="rss2" label="RSS 2.0" />
                <el-option value="atom" label="Atom" />
                <el-option value="rss1" label="RSS 1.0" />
                <el-option value="unknown" label="未知" />
              </el-select>
            </el-form-item>
          </div>

          <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
            <el-form-item label="来源类型" prop="rssSourceType">
              <el-select v-model="model.rssSourceType" class="w-full">
                <el-option value="direct" label="Direct" />
                <el-option value="rsshub" label="RSSHub" />
                <el-option value="other" label="Other" />
              </el-select>
            </el-form-item>
            <el-form-item label="类别" prop="categoryId">
              <el-select v-model="model.categoryId" clearable placeholder="可选" class="w-full">
                <el-option v-for="c in categoryOptions" :key="c.id" :label="c.name" :value="c.id" />
              </el-select>
            </el-form-item>
          </div>

          <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
            <el-form-item label="信源" prop="sourceId">
              <el-select v-model="model.sourceId" clearable placeholder="可选" class="w-full">
                <el-option v-for="s in sourceOptions" :key="s.id" :label="s.name" :value="s.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="地区" prop="regionId">
              <el-select v-model="model.regionId" clearable placeholder="可选" class="w-full">
                <el-option v-for="r in regionOptions" :key="r.id" :label="r.name" :value="r.id" />
              </el-select>
            </el-form-item>
          </div>

          <el-form-item label="备注" prop="remark">
            <el-input v-model="model.remark" type="textarea" :autosize="{ minRows: 6, maxRows: 12 }" />
          </el-form-item>

          <div class="flex justify-end">
            <el-button @click="$emit('cancel')">取消</el-button>
            <el-button type="primary" :loading="submitting" @click="submit">保存</el-button>
          </div>
        </div>
      </el-card>

      <!-- 右侧：元数据展示 -->
      <el-card shadow="never" class="form-card">
        <template #header>
          <h3 class="text-lg font-semibold">元数据信息</h3>
        </template>
        <el-descriptions :column="1" border>
          <el-descriptions-item label="ID">{{ model.id ?? '-' }}</el-descriptions-item>
          <el-descriptions-item label="状态">{{ model.status === 1 ? '启用' : '禁用' }}</el-descriptions-item>
          <el-descriptions-item label="类别">{{ getCategoryName(model.categoryId) }}</el-descriptions-item>
          <el-descriptions-item label="信源">{{ getSourceName(model.sourceId) }}</el-descriptions-item>
          <el-descriptions-item label="地区">{{ getRegionName(model.regionId) }}</el-descriptions-item>
          <el-descriptions-item label="上次抓取日期">{{ formatDate(model.lastFetchDate) }}</el-descriptions-item>
          <el-descriptions-item label="上次抓取时间">{{ formatDateTime(model.lastFetchAt) }}</el-descriptions-item>
          <el-descriptions-item label="上次错误时间">{{ formatDateTime(model.lastErrorAt) }}</el-descriptions-item>
          <el-descriptions-item label="错误次数">{{ model.errorCount ?? 0 }}</el-descriptions-item>
          <el-descriptions-item label="抓取次数">{{ model.fetchCount ?? 0 }}</el-descriptions-item>
          <el-descriptions-item label="ETag">{{ model.etag || '-' }}</el-descriptions-item>
          <el-descriptions-item label="Last-Modified">{{ model.lastModified || '-' }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatDateTime(model.createdAt) }}</el-descriptions-item>
          <el-descriptions-item label="修改时间">{{ formatDateTime(model.updatedAt) }}</el-descriptions-item>
        </el-descriptions>
      </el-card>
    </div>
  </el-form>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue'
import { categoryAPI, sourceAPI, regionAPI } from '@/services/api'

const props = defineProps({
  modelValue: { type: Object, default: () => ({}) },
  loading: { type: Boolean, default: false }
})
const emit = defineEmits(['update:modelValue', 'submit', 'cancel'])

const formRef = ref(null)
const model = ref({
  name: '',
  url: '',
  status: 1,
  fetchTime: '08:00:00',
  rssVersion: 'rss2',
  rssSourceType: 'direct',
  categoryId: null,
  sourceId: null,
  regionId: null,
  remark: ''
})
const time = ref('08:00:00')
const submitting = ref(false)

// 选项数据
const categoryOptions = ref([])
const sourceOptions = ref([])
const regionOptions = ref([])

const rules = {
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
  url: [{ required: true, message: '请输入RSS地址', trigger: 'blur' }],
}

watch(() => props.modelValue, (val) => {
  if (val) {
    model.value = { ...model.value, ...val }
    time.value = val.fetchTime || model.value.fetchTime
  }
}, { immediate: true })

watch(time, (val) => {
  model.value.fetchTime = val
})

const submit = () => {
  formRef.value.validate(async (valid) => {
    if (!valid) return
    submitting.value = true
    try {
      emit('submit', { ...model.value })
    } finally {
      submitting.value = false
    }
  })
}

onMounted(() => {})

// 加载下拉选项数据
onMounted(async () => {
  try {
    const [cats, sources] = await Promise.all([
      categoryAPI.getCategories(),
      sourceAPI.getSources()
    ])
    categoryOptions.value = Array.isArray(cats) ? cats : []
    sourceOptions.value = Array.isArray(sources) ? sources : []

    const regionsResp = await regionAPI.getAllRegions()
    if (regionsResp && regionsResp.code === 200) {
      regionOptions.value = regionsResp.data || []
    }
  } catch (e) {
    // 静默失败，不阻塞表单使用
  }
})

// 名称与时间格式化
const getCategoryName = (id) => {
  if (!id) return '-'
  const c = categoryOptions.value.find(x => x.id === id)
  return c ? c.name : '-'
}
const getSourceName = (id) => {
  if (!id) return '-'
  const s = sourceOptions.value.find(x => x.id === id)
  return s ? s.name : '-'
}
const getRegionName = (id) => {
  if (!id) return '-'
  const r = regionOptions.value.find(x => x.id === id)
  return r ? r.name : '-'
}
const formatDate = (val) => {
  if (!val) return '-'
  try {
    const d = new Date(val)
    if (Number.isNaN(d.getTime())) return String(val)
    const pad = (n) => String(n).padStart(2, '0')
    return `${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())}`
  } catch {
    return String(val)
  }
}
const formatDateTime = (val) => {
  if (!val) return '-'
  try {
    const d = new Date(val)
    if (Number.isNaN(d.getTime())) return String(val)
    const pad = (n) => String(n).padStart(2, '0')
    return `${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`
  } catch {
    return String(val)
  }
}
</script>

<style scoped>
.form-card :deep(.el-card__header) {
  border-bottom: 1px solid var(--el-border-color-lighter);
}
</style>



